package com.etop.controller;

import com.etop.beans.Activity;
import com.etop.beans.Borrow;
import com.etop.beans.Goods;
import com.etop.beans.ProFile;
import com.etop.beans.Pro_schedule;
import com.etop.beans.Project;
import com.etop.beans.User;
import com.etop.dto.UserGoodsDTO;
import com.etop.service.ManagerService;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

@Controller
@SessionAttributes({"loginUser", "users"})
public class ManagerController {

    @Resource(name = "managerService")           // 注入userService对象，new userService()在applicationContext.xml中配置
    private ManagerService managerService;

    public void setManagerService(ManagerService managerService) {
        this.managerService = managerService;
    }

    /**
     * 管理员查看所有的项目
     *
     * @param model
     * @return
     */
    @RequestMapping(value = {"/adminProjectManagement"}, method = RequestMethod.GET)
    public String adminProjectManagement(Model model) {
        System.out.println("adminProject");
        List<Project> pros = managerService.listOfProject();
        List<Pro_schedule> sches = managerService.listOfProSchedule();

        model.addAttribute("adminpros", pros);
        for (Project pros1 : pros) {
            pros1.setListOfLeaders(managerService.listLeadersOfOneProject(pros1));
            pros1.setListOfMembers(managerService.listMembersOfOneProject(pros1));
            pros1.setListOfSchedules(managerService.listSchedulesOfOneProject(sches, pros1));
        }
        return "admin/adminProjectManagement";
    }

    /**
     * 管理员查看所有的项目
     *
     * @param model
     * @return
     */
    @RequestMapping(value = {"/adminProjectManagement"}, method = RequestMethod.POST)
    public String adminProjectManagement(int acti_id, Model model) {
        System.out.println("adminProject");
        List<Project> pros = managerService.listOfProject();
        List<Pro_schedule> sches = managerService.listOfProSchedule();

        model.addAttribute("adminpros", pros);
        for (Project pros1 : pros) {
            pros1.setListOfLeaders(managerService.listLeadersOfOneProject(pros1));
            pros1.setListOfMembers(managerService.listMembersOfOneProject(pros1));
            pros1.setListOfSchedules(managerService.listSchedulesOfOneProject(sches, pros1));
        }
        for (Project pro : pros) {
            if (pro.getId() == acti_id) {
                model.addAttribute("pro_sche", pro.getListOfSchedules());
                break;
            }
        }

        return "admin/detailInformation";
    }

    /**
     * 删除工程
     *
     * @param pid
     * @param model
     * @return
     */
    @RequestMapping(value = {"/deleteProjectManagement"}, method = RequestMethod.POST)
    public String deleteProjectManagement(int pid, Model model) {
        managerService.deleteOneProject(pid);

        List<Project> pros = managerService.listOfProject();
        List<Pro_schedule> sches = managerService.listOfProSchedule();

        model.addAttribute("adminpros", pros);
        for (Project pros1 : pros) {
            pros1.setListOfLeaders(managerService.listLeadersOfOneProject(pros1));
            pros1.setListOfMembers(managerService.listMembersOfOneProject(pros1));
            pros1.setListOfSchedules(managerService.listSchedulesOfOneProject(sches, pros1));
        }

        return "admin/adminProjectManagement";
    }

    /**
     * 跳转去上传界面
     *
     * @param m 用于向界面中传送项目的信息
     * @return
     */
    @RequestMapping(value = {"/adminUpload"}, method = RequestMethod.GET)
    public String fileUpload(Model m) {
        List<Project> projectList = managerService.listProject();
        m.addAttribute("adminProjectList", projectList);
        return "admin/adminUpload";
    }

    /**
     * 处理上传
     *
     * @param proID 添加文件的项目的id
     * @param multipartFile 里面包含要上传的文件
     * @param request
     * @return
     */
    @RequestMapping(value = {"/adminUpload"}, method = RequestMethod.POST)
    public String fileUpload(int proID, MultipartFile multipartFile, HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("loginUser");
        managerService.addProFile(proID, multipartFile, request.getContextPath(), user.getUserName());
        return "admin/login";
    }

    /**
     * 跳转到查看文件的页面
     *
     * @param proName 文件所在的项目名（可不要）
     * @param m
     * @return
     */
    @RequestMapping(value = {"/adminCheckFile"}, method = RequestMethod.GET)
    public String checkFile(String proName, Model m) {
        if (proName == null) {
            proName = "";
        }
        List<ProFile> proFileList = managerService.listProFile(proName);
        m.addAttribute("adminProFileList", proFileList);
        return "admin/adminCheckFile";
    }

    /**
     * 处理下载
     *
     * @param proFileId 下载文件的id
     * @param response 获取输出流
     */
    @RequestMapping(value = {"/adminDownLoadFile"}, method = RequestMethod.POST)
    public String downLoadFile1(int proFileId, HttpServletResponse response, Model model) {
        managerService.downLoadFile(proFileId, response);
        return "admin/adminCheckFile";
    }

    @RequestMapping(value = {"/updateUser.do"}, method = RequestMethod.POST)
    public String updateUser(int userId, Model model) {
        User user = managerService.loadUser(userId);
        model.addAttribute(user);
        return "admin/updateUser";
    }

    @RequestMapping(value = {"/updateUser"}, method = RequestMethod.POST)
    public String updateUserConfirm(User user, Model model) {
        managerService.updateInfo(user);
        return "admin/login";
    }

    @RequestMapping(value = {"/deleteUser.do"}, method = RequestMethod.POST)
    public String deleteUser(int userId, Model model) {
        managerService.deleteUser(userId);
        List<User> users = (List<User>) model.asMap().get("users");
        for (int i = 0; i < users.size(); i++) {
            if (users.get(i).getId() == userId) {
                users.remove(i);
            }
        }
        model.asMap().replace("users", users);
        return "admin/login";
    }

    @RequestMapping(value = {"/adminAddGoods"}, method = RequestMethod.GET)
    public String addGoods() {
        return "admin/AddGoods";
    }

    /**
     * 添加物品
     *
     * @param name
     * @param description
     * @return
     */
    @RequestMapping(value = {"/adminAddGoods"}, method = RequestMethod.POST)
    public String addGoods(String name, String description) {
        Goods g = new Goods();
        g.setName(name);
        g.setDescription(description);
        managerService.addGoods(g);

        return "redirect:/adminGoodsCenter";
    }

    /**
     * 更新物品信息
     *
     * @param name
     * @param description
     * @param id
     * @return
     */
    @RequestMapping(value = {"/adminUpdateGoods"}, method = RequestMethod.POST)
    public String updateGoods(String name, String description, int id
    ) {
        Goods g = new Goods();
        g.setName(name);
        g.setDescription(description);
        g.setId(id);
        System.out.println(g);
        managerService.updateGoods(g);
        return "redirect:/adminGoodsCenter";
    }

    /**
     * 删除物品
     *
     * @param id
     * @return
     */
    @RequestMapping(value = {"/adminDelGoods"}, method = RequestMethod.POST)
    public String deleteGoods(int id
    ) {
        Goods g = new Goods();
        g.setId(id);
        managerService.deleteGoods(g);
        return "redirect:/adminGoodsCenter";
    }

    /**
     * 列举出所有物品，跳转到物品中心
     *
     * @param key
     * @param model
     * @return
     */
    @RequestMapping(value = {"/adminGoodsCenter"}, method = RequestMethod.GET)
    public String listGoods(String key, Model model
    ) {
        if (key == null) {
            key = "";
        }
        model.addAttribute("listUserGoodsDTO", managerService.listGoods(key));
        return "admin/GoodsCenter";
    }

    @RequestMapping(value = {"/adminGoodsChact"}, method = RequestMethod.GET)
    public String chactGoods(int isReturn, int gid, int bid, Model model
    ) {
        Borrow b;
        if (isReturn == 0) {
            b = managerService.loadBorrowById(bid);
        } else {
            Goods g = managerService.loadGoodsById(gid);
            b = new Borrow();
            b.setGoods(g);
            b.setIsReturn(isReturn);
        }
        model.addAttribute("borrow", b);
        System.out.println(b);
        return "admin/GoodsInformation";
    }

    @RequestMapping(value = {"/adminAddActivity"}, method = RequestMethod.GET)
    public String addActivity() {
        return "admin/AddActivity";
    }

    /**
     * 添加活动
     *
     * @param name
     * @param description
     * @param s_time
     * @param e_time
     * @return
     */
    @RequestMapping(value = {"/adminAddActivity"}, method = RequestMethod.POST)
    public String addActivity(String name, String description, String s_time, String e_time
    ) {

        Date st_time = null;
        Date end_time = null;
        try {
            st_time = DateFormat.getDateInstance().parse(s_time);
            end_time = DateFormat.getDateInstance().parse(e_time);
        } catch (ParseException ex) {
            Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
        }

        Activity act = new Activity();
        act.setName(name);
        act.setDescription(description);
        act.setS_time(st_time);
        act.setE_time(end_time);

        managerService.addActivity(act);
        return "redirect:/adminActivityCenter";
    }

    /**
     * 更新活动信息
     *
     * @param name
     * @param description
     * @param id
     * @param s_time
     * @param e_time
     * @return
     */
    @RequestMapping(value = {"/adminUpdateActivity"}, method = RequestMethod.POST)
    public String updateActivity(String name, String description, int id, String s_time, String e_time
    ) {

        Date st_time = null;
        Date end_time = null;
        try {
            st_time = DateFormat.getDateInstance().parse(s_time);
            end_time = DateFormat.getDateInstance().parse(e_time);
        } catch (ParseException ex) {
            Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex);
        }

        Activity act = new Activity();
        act.setName(name);
        act.setDescription(description);
        act.setS_time(st_time);
        act.setE_time(end_time);
        act.setId(id);

        managerService.updateActivity(act);
        return "redirect:/adminActivityCenter";
    }

    /**
     * 删除活动
     *
     * @param id
     * @return
     */
    @RequestMapping(value = {"/adminDelActivity"}, method = RequestMethod.POST)
    public String deleteActivity(int id
    ) {
        Activity act = new Activity();
        act.setId(id);
        managerService.deleteActivity(act);
        return "redirect:/adminActivityCenter";
    }

    /**
     * 列举出所有活动，跳转到活动中心
     *
     * @param key
     * @param model
     * @return
     */
    @RequestMapping(value = {"/adminActivityCenter"}, method = RequestMethod.GET)
    public String listActivity(String key, Model model) {
        if (key == null) {
            key = "";
        }
        model.addAttribute("listActivity", managerService.listActivity(key));
        return "admin/ActivityCenter";
    }

    @RequestMapping(value = {"/adminActivityChact"}, method = RequestMethod.POST)
    public String chactActivity(int aid, Model model
    ) {
        model.addAttribute("act", managerService.getActivityById(aid));
        return "admin/ActivityInformation";
    }
}
